package org.graffitidiary.activity;

import java.util.ArrayList;
import java.util.List;

import org.graffitidiary.R;
import org.graffitidiary.bean.Brush;
import org.graffitidiary.bean.FileInfo;
import org.graffitidiary.bean.JsonRootBean;
import org.graffitidiary.dialogfragment.EditGraffitiNameDialogFragment;
import org.graffitidiary.dialogfragment.SelfDialog;
import org.graffitidiary.framework.ui.ActionBarActivity;
import org.graffitidiary.manager.Dbs;
import org.graffitidiary.utils.FileMethod;
import org.graffitidiary.utils.GloableParams;
import org.graffitidiary.utils.ToastUtil;
import org.graffitidiary.view.SecondSurfaceView;
import org.json.JSONArray;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.exception.DbException;
import com.okhttplib.HttpInfo;
import com.okhttplib.OkHttpUtil;
import com.okhttplib.callback.ProgressCallback;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AutoDrawActivity extends ActionBarActivity{
    private List<Brush> brushs = new ArrayList<Brush>();
    SecondSurfaceView surfaceView;
    String fileName;
    String filePath;
    String fileNick;
    String fileState;
    String fileid;
    ProgressBar mProgressBar;

    private ImageView iv_start;//开始

    private boolean sfplay = true;
    private boolean sfplay2 = true;

    private EditGraffitiNameDialogFragment dialogFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showBar();
        setBarTitle("动画");
        String Name = getIntent().getStringExtra("Name");//获取传递过来的文件名
        fileName = getIntent().getStringExtra("fileName");//获取传递过来的文件名
        filePath = getIntent().getStringExtra("filePath");//获取传递过来的文件地址
        fileNick = getIntent().getStringExtra("fileNick");//获取传递过来的文件地址
        fileState = getIntent().getStringExtra("fileState");//获取传递过来的文件状态
        fileid = getIntent().getStringExtra("id");//获取传递过来的文件id

        String path = GloableParams.localFile + Name + ".xml";
        if("bsnd".equals(fileName)){//判断是从网络过来的涂鸦还是本地涂鸦
            hideBarRightImgBtn();
            String newFile = filePath.replace("./text/", "");
            path = GloableParams.localFile + newFile;
            if(!FileMethod.fileIsExists(path)){//判断网络涂鸦是否有缓存
                downLoading(GloableParams.PROXY_IP + filePath, newFile.replace(".xml",""));
                iv_start.setVisibility(View.GONE);
                mProgressBar.setVisibility(View.VISIBLE);
            }
            fileName = newFile;
        }else{//如果不是网络涂鸦
            if("0".equals(fileState)){//判断本地数据库状态是否为0，0为用户绘制未上传
                showBarRightImgBtn();
                setBarRightBackgroundResource(R.drawable.share);
            }else{//如果不是0则隐藏右上角的分享图标
                hideBarRightImgBtn();
            }
        }
//		tuyariji
    }

    /**
     * 下载文件
     * @param fileNetPath 网络地址
     * @param name 文件名
     */
    private void downLoading(String fileNetPath, String name) {
        HttpInfo info = HttpInfo.Builder()
                .addDownloadFile(fileNetPath, name, new ProgressCallback(){
                    @Override
                    public void onProgressMain(int percent, long bytesWritten, long contentLength, boolean done) {
                        mProgressBar.setProgress(percent);//使用okhttp监听下载状态
                    }
                    @Override
                    public void onResponseMain(String filePath, HttpInfo info) {
                        mProgressBar.setVisibility(View.GONE);//隐藏下载进度条
                        iv_start.setVisibility(View.VISIBLE);//显示开始按钮
                    }
                }).build();
        OkHttpUtil.Builder().setReadTimeout(120).build(this).doDownloadFileAsync(info);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_auto_draw;
    }

    @Override
    protected void initViews() {
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        surfaceView = (SecondSurfaceView) findViewById(R.id.surfaceview);
        iv_start = (ImageView) findViewById(R.id.iv_start);
        iv_start.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_start:
                if(sfplay){//开始播放并读取文件
                    iv_start.setImageResource(R.drawable.tmddx);
                    try {
                        String read = FileMethod.readTxtFile(fileName);
                        JSONArray array = new JSONArray(read);
                        for(int i = 0;i<array.length();i++){
                            JSONObject Object = array.getJSONObject(i);
                            String b = Object.getString("Brush");
                            Brush brush = JSON.parseObject(b, Brush.class);
                            brushs.add(brush);
                        }
                        surfaceView.autoDraw(brushs);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    sfplay = false;
                }else{//暂停播放
                    if(sfplay2){//开始
                        iv_start.setImageResource(R.drawable.start);
                        surfaceView.pause();
                        sfplay2 = false;
                    }else{//暂停
                        iv_start.setImageResource(R.drawable.tmddx);
                        surfaceView.ct();
                        sfplay2 = true;
                    }
                }
                break;

            case R.id.bar_btn_right://又上脚分享按钮
                if(null == GloableParams.token || "".equals(GloableParams.token)){//判断用户是否登陆
                    Toast.makeText(AutoDrawActivity.this, "还未登陆", Toast.LENGTH_SHORT);
                    startIntent(LoginActivity.class);
                }else{//如果登陆就弹出命名框
                    dialogFragment = new EditGraffitiNameDialogFragment(AutoDrawActivity.this, fileNick);
                    dialogFragment.show(getFragmentManager(), "BasicInfoDialogFragment");
//                    selfDialog = new SelfDialog(AutoDrawActivity.this);
//                    selfDialog.setTitle("编辑");
//                    selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
//                        @Override
//                        public void onYesClick() {
//                            String name = selfDialog.getMsg();
//                            if(!TextUtils.isEmpty(name)){
//                                setGraffitiName(name);
//                                selfDialog.dismiss();
//                            }else{
//                                ToastUtil.showLongToast("请输入昵称");
//                            }
//                        }
//                    });
//                    selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
//                        @Override
//                        public void onNoClick() {
//                            selfDialog.dismiss();
//                        }
//                    });
//                    selfDialog.show();
                }
                break;
        }
    }
    private SelfDialog selfDialog;

    private String GraffitiName = "";
    /**
     * 设置文件名，用于放置到服务器
     * @param name
     */
    public void setGraffitiName(String name) {
        showProgressDialog();
        GraffitiName = name;
        uploadFile(filePath, GraffitiName);
    }

    /**
     * 上传文件
     * @param path 本地文件地址
     * @param GraffitiName 文件名
     */
    private void uploadFile(String path, String GraffitiName) {
        if(TextUtils.isEmpty(path)){
            return;
        }

        HttpInfo info = HttpInfo.Builder()
                .setUrl(GloableParams.PROXY_IP + "ExchangeDiary.php")
                .addParam("token", GloableParams.token)
                .addParam("city", "温州")
                .addParam("graffitiname", GraffitiName)
                .addUploadFile("uploadedfile",path,new ProgressCallback(){
                    @Override
                    public void onProgressMain(int percent, long bytesWritten, long contentLength, boolean done) {
                        System.out.println("上传进度：" + percent);
                    }

                    @Override
                    public void onResponseSync(String filePath, HttpInfo info) {
                        super.onResponseSync(filePath, info);
                        closeProgressDialog();
                        if (info.isSuccessful()) {
                            JsonRootBean bean = JSON.parseObject(info.getRetDetail(), JsonRootBean.class);
                            String code = bean.getCode();
                            if("202".equals(code)){
                                ToastUtil.showLongToast(bean.getMessage());
                                startIntent(LoginActivity.class);
                            }else if("200".equals(code)){//上传成功改变本地数据状态
                                updateFileInfo(fileid);
                                ToastUtil.showLongToast(bean.getMessage());
                                finish();
                            }else if("204".equals(code)){//上传成功改变本地数据状态
                                updateFileInfo(fileid);
                                ToastUtil.showLongToast(bean.getMessage());
                                finish();
                            }
                        } else {
                            ToastUtil.showShortToast(info.getRetDetail());
                        }
                    }

                })
                .build();
        OkHttpUtil.getDefault(this).doUploadFileAsync(info);
    }

    /**
     * 修改用户本地文件上传后的数据状态
     */
    private void updateFileInfo(String id) {
        try {
            Dbs.getDb(this);
            FileInfo fileInfo = Dbs.getDb().findById(FileInfo.class, id);
            if(fileInfo != null){
                fileInfo.setFileState(1);
                Dbs.getDb().update(fileInfo);
            }
            Dbs.close();
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 销毁后将绘制的线程也停止
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        surfaceView.onDestory();
    }

}
